﻿using System;
using System.Collections;
using System.ComponentModel;
#if NETFX_CORE
using Windows.UI.Core;
#else
using System.Windows.Threading;
#endif

namespace FreshMeat.Xaml
{
   /// <summary>
   /// A base class for a view model in an MVVM application.
   /// Implements <see cref="INotifyPropertyChanged"/> so the model can report changes to the view
   /// and <see cref="INotifyDataErrorInfo"/> so the model can report validation errors to the view.
   /// </summary>
   public abstract class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
   {
#if NETFX_CORE
      readonly CoreDispatcher dispatcher;
#else
      readonly Dispatcher dispatcher;
#endif
      readonly PropertyNotifier propertyProps;
      readonly ErrorNotifier errorNotifier;
 
      protected ViewModel()
      {
#if NETFX_CORE
         dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
#elif SILVERLIGHT
         dispatcher = System.Windows.Deployment.Current != null ? System.Windows.Deployment.Current.Dispatcher : null;
#else
         dispatcher = Dispatcher.CurrentDispatcher; 
#endif

         propertyProps = new PropertyNotifier(this, dispatcher, () => PropertyChanged);
         errorNotifier = new ErrorNotifier(this, dispatcher, () => ErrorsChanged, propertyName => propertyProps.Changed(propertyName));
      }

      protected PropertyNotifier Props
      {
         get { return propertyProps; }
      }

      protected ErrorNotifier Errors
      {
         get { return errorNotifier; }
      }

      public event PropertyChangedEventHandler PropertyChanged;

      public bool HasErrors
      {
         get { return errorNotifier.HasErrors; }
      }

      public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

      public IEnumerable GetErrors(string propertyName)
      {
         return errorNotifier.GetErrors(propertyName);
      }
   }
}
